package com.tuo51.components.intercepter;

import com.tuo51.foudation.model.MemVerificationCache;
import com.tuo51.foudation.utils.DateUtil;
import com.tuo51.foudation.utils.IpHelper;
import com.tuo51.foudation.utils.ModelUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class ActionLogInterceptor implements HandlerInterceptor {

    @Autowired
    private MemVerificationCache memVerificationCache;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestUrl = request.getRequestURI();
        String staffId = "";
        String ticket = "";
        if (request.getHeader("ticket") != null && StringUtils.isNotBlank(request.getHeader("ticket")) ){
            ticket =  request.getHeader("ticket");
            staffId = memVerificationCache.getStaffIdWithNoException(ticket);
        }
        String ip = IpHelper.getRequestIpAddr(request);
        String params = ModelUtil.objectMapper.writeValueAsString(request.getParameterMap());
        log.info("request ticket:[{}], staffId:[{}], URL:[{}] ,params:[{}], request ip :[{}], date:[{}]", ticket, staffId, requestUrl, params, ip, DateUtil.millisToDateTime(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"));

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
